/**
 * Created by Ysssssss on 2021/5/2.
 */

import React, { PureComponent } from 'react'
import PropTypes from 'prop-types';
import {CustomizeDndProvider, DraggableDiv} from "@common/presentational/DndSort";
import {moveToNewIndex} from "@utils/arrayHelper";
import {Button, Form, Input, Radio} from "antd";
import ImageUpload from "@common/presentational/ImageUpload";
import DoubleCheck from "@common/presentational/DoubleCheck";
import ProductChoose from "@components/shoppingMall/design/ProductChoose";

class MenuListModule extends PureComponent {
    static propTypes = {
        menuInfo: PropTypes.object,
        index: PropTypes.number,
        onChange: PropTypes.func
    }

    constructor(props) {
        super(props);
        this.state = {
            createTag: false
        }

        this.menuRef = {}
    }

    toggleCreateTag (value) {
        this.setState({
            createTag: value
        })
    }

    sortList (dragId, hoverId) {
        const { index, menuInfo, onChange } = this.props
        const { menuList } = menuInfo
        let dragIndex = 0
        let hoverIndex = 0
        menuList.forEach((item, i) => {
            if(item.name === dragId) {
                dragIndex = i
            }
            if(item.name === hoverId) {
                hoverIndex = i
            }
        })
        onChange && onChange(index, {
            ...menuInfo,
            menuList: moveToNewIndex(menuList, dragIndex, hoverIndex)
        })
    }



    editSubmit (values, i) {
        const { onChange, menuInfo, index } = this.props
        if (i < 0) {
            onChange && onChange(index, {
                ...menuInfo,
                menuList: [
                    ...menuInfo.menuList,
                    values,
                ]
            })
            this.toggleCreateTag(false)
        } else {
            onChange && onChange(index, {
                ...menuInfo,
                menuList: [
                    ...menuInfo.menuList.slice(0, i),
                    values,
                    ...menuInfo.menuList.slice(i + 1),
                ]
            })
        }
    }

    deleteSubmit(i) {
        const { onChange, menuInfo, index } = this.props
        onChange && onChange(index, {
            ...menuInfo,
            menuList: [
                ...menuInfo.menuList.slice(0, i),
                ...menuInfo.menuList.slice(i + 1),
            ]
        })
    }

    render () {
        const { menuInfo } = this.props
        const { createTag } = this.state
        const names = (menuInfo.menuList || []).map(item => item.name)
        return (
            <div className="operation-container ft-clr-d">
                <div className="ft-16 pdb-8">图文导航</div>
                <div className="ft-12 pdb-16 bdb-l ft-clr-ml">最多添加4个</div>
                <div className="mgt-24">
                    <CustomizeDndProvider>
                        { (menuInfo.menuList || []).map((menu, index) => {
                            if (!this.menuRef[menu.name]) {
                                this.menuRef[menu.name] = React.createRef()
                            }
                            return (
                                <DraggableDiv
                                    key={menu.name}
                                    id={menu.name}
                                    type="menuList"
                                    dragRef={this.menuRef[menu.name]}
                                    moveItemFunc={this.sortList.bind(this)}
                                >
                                    <MenuEditInfo
                                        menuInfo={menu}
                                        index={index}
                                        names={[
                                            ...names.slice(0, index),
                                            ...names.slice(index + 1)
                                        ]}
                                        editSubmit={this.editSubmit.bind(this)}
                                        deleteSubmit={this.deleteSubmit.bind(this)}
                                        dragRef={this.menuRef[menu.name]}
                                    />
                                </DraggableDiv>
                            )
                        }) }
                    </CustomizeDndProvider>
                    { createTag ? (
                        <MenuEditInfo
                            toggleCreateTag={this.toggleCreateTag.bind(this, false)}
                            index={-1}
                            names={names}
                            editSubmit={this.editSubmit.bind(this)}
                        />
                    ) : null }
                    <Button className="button-large w-100 mgt-16"
                            onClick={this.toggleCreateTag.bind(this, true)}
                            disabled={createTag || menuInfo.menuList.length >= 4}
                    >添加导航</Button>
                </div>
            </div>
        )
    }
}

const initMenuInfo = {
    name: '', // 名称
    picture: '', // 图片
    navType: 'goods-seo', // 跳转类型，取值：NAV_TYPE
    goods: [], // 商品id
}
class MenuEditInfo extends PureComponent {
    static propTypes = {
        menuInfo: PropTypes.object,
        index: PropTypes.number,
        editSubmit: PropTypes.func,
        deleteSubmit: PropTypes.func,
        toggleCreateTag: PropTypes.func,
        names: PropTypes.array,
        dragRef: PropTypes.object
    }

    constructor(props) {
        super(props);
        this.state = {
            isEdit: !props.menuInfo,
            hackMenuInfo: props.menuInfo || initMenuInfo
        }
        this.formRef = React.createRef()
    }

    toggleEditMode (value) {
        const { menuInfo, index } = this.props
        this.setState({
            isEdit: value,
            hackMenuInfo: value ? (menuInfo || initMenuInfo) : this.state.hackMenuInfo
        }, () => {
            if (!value && index < 0) {
                this.props.toggleCreateTag()
            }
        })
    }

    submitForm (values) {
        const { index } = this.props
        this.toggleEditMode(false)
        this.props.editSubmit(values, index)
    }

    handleSubmit () {
        this.formRef.current?.submit()
    }

    deleteSubmit () {
        const { index } = this.props
        this.props.deleteSubmit(index)
    }

    render () {
        const { menuInfo, index, names, dragRef } = this.props
        const { isEdit, hackMenuInfo } = this.state

        return isEdit ? (
            <div className="operation-block-bg mgt-16 pd-16 pdt-24 pdb-24">
                <Form
                    ref={this.formRef}
                    name="menu-edit"
                    labelCol={{ span: 6 }}
                    wrapperCol={{ span: 18 }}
                    initialValues={hackMenuInfo}
                    requiredMark={false}
                    onFinish={this.submitForm.bind(this)}
                >
                    <Form.Item
                        label='导航'
                        name='name'
                        rules={[
                            { required: true, message: '请输入广告标题' },
                            {
                                validator: (_, value) =>
                                    names.includes(value) ? Promise.reject(new Error(`广告标题已存在`)) : Promise.resolve(),
                            }
                        ]}
                        className="mgb-24"
                    >
                        <Input maxLength={5} />
                    </Form.Item>
                    <Form.Item
                        label='图片'
                        name='picture'
                        className="mgb-24"
                    >
                        <ImageUpload
                            accept='image/png, image/jpeg, image/jpg'
                            maxFileSize="2m"
                            uploadIntro={(
                                <div className="ft-12 ft-clr-ml mgl-16" style={{width: '140px'}}>
                                    支持PNG、JPG格式，不超过2MB，建议尺寸686*160PX
                                </div>
                            )}
                        />
                    </Form.Item>
                    <Form.Item
                        label='链接'
                        name='navType'
                        className="mgb-24"
                    >
                        <Radio.Group>
                            <Radio value="goods-seo">商品推广</Radio>
                            <Radio value="live">直播</Radio>
                        </Radio.Group>
                    </Form.Item>
                    <Form.Item
                        label=''
                        labelCol={{ span: 0 }}
                        wrapperCol={{ span: 24 }}
                        name='goods'
                        className="mgb-24"
                    >
                        <ProductChoose />
                    </Form.Item>
                    <div className="flex-row-right">
                        <Button className="mgr-16" onClick={this.toggleEditMode.bind(this, false)}>取消</Button>
                        <Button type="primary" onClick={this.handleSubmit.bind(this)}>确定</Button>
                    </div>

                </Form>
            </div>
        ) : ( index < 0 ? null : (
            <div className="flex-row-between operation-block-bg mgt-16 pd-16" ref={dragRef}>
                <div className="flex-vertical-center">
                    <div>{ menuInfo.name }</div>
                    { menuInfo.startDate ? (
                        <div>{ menuInfo.startDate } - { menuInfo.endDate }</div>
                    ) : null }
                </div>
                <div className="flex-vertical-center">
                    <span className="pdl-8 pdr-8 cur-poi" onClick={this.toggleEditMode.bind(this, true)}>编辑</span>
                    <DoubleCheck title="是否确认删除该导航配置"
                                 onClick={this.deleteSubmit.bind(this)}
                    >
                        <span className="pdl-8 pdr-8 cur-poi bdl-l">删除</span>
                    </DoubleCheck>
                </div>
            </div>
        ))
    }

}

export default MenuListModule

export class MenuListPreview extends PureComponent {
    static propTypes = {
        menuInfo: PropTypes.object,
        onClick: PropTypes.func,
        className: PropTypes.string,
    }

    render () {
        const { onClick, menuInfo, className } = this.props
        const defaultMenuList = menuInfo.menuList.length < 3 ? new Array(3 - menuInfo.menuList.length).fill({
            icon: '',
            name: '名称'
        }) : []

        return (
            <div className={`menu-list-preview cur-poi ${className}`} onClick={onClick}>
                { menuInfo.menuList.map(menu => (
                    <div className="menu-item" key={menu.name}>
                        { menu.icon ? (
                            <div className="menu-item-img">
                                <img src={menu.icon} alt=""/>
                            </div>
                        ) : (
                            <div className="menu-item-img empty-bg" />
                        ) }
                        <div className="menu-item-text">{ menu.name }</div>
                    </div>
                ))}
                { defaultMenuList.map((menu, index) => (
                    <div className="menu-item" key={`default_${index}`}>
                        <div className="menu-item-img empty-bg" />
                        <div className="menu-item-text">{ menu.name }{index}</div>
                    </div>
                )) }
            </div>
        )
    }
}